package com.zline.foodraise.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.zline.foodraise.R;
import com.zline.foodraise.entity.TemplateBean;
import com.zline.foodraise.listener.GestureListener;
import com.zline.foodraise.util.DeviceUtil;
import com.zline.foodraise.util.ImageUtil;

/**
 * Created by heshantao on 15/10/28.
 * 自定义海报模板
 */
public class PosterTemplateView extends View {
    private static final String LOG_TAG = PosterTemplateView.class.getSimpleName();
    TemplateBean templateBean;
    //本地相册中的图片
    String mLocPath;
    private GestureDetector gestures;
    private Matrix translate;
    //本地相册所选图片的缩放矩阵
    private Matrix dragPicMatrix, templatePicMatrix;
    private Bitmap dragBitmap;
    Bitmap templateBitmap;
    Context cxt;
    private Matrix animateStart;
    private Interpolator animateInterpolator;
    private long startTime;
    private long endTime;
    private float totalAnimDx;
    private float totalAnimDy;
    //可以移动的左上X坐标
    float leftTopX;
    //可以移动的左上Y坐标
    float leftTopY;
    //可以移动的右下X坐标
    float rightBottomX;
    //可以移动的右下Y坐标
    float rightBottomY;
    //模板数据的原始像素密度
    //预留的边界
    final float defaultBorder = 10;
    ImageUtil imageUtil;
    //设备宽，高
    int deviceHeight;
    //设备密度
    float density;
    //空余的高度
    int spaceHeight = 220;
    //自定义当前View 的宽度、高度
    int viewWidht, viewHeight;
    //模板图片的压缩
    public float templateScale;

    public PosterTemplateView(Context context, TemplateBean template, String locPath,Bitmap bitmap) {
        super(context);
        this.templateBean = template;
        this.mLocPath = locPath;
        this.cxt = context;
        imageUtil = new ImageUtil();
        translate = new Matrix();
        density = DeviceUtil.getDeviceDesity(cxt);
        deviceHeight = DeviceUtil.getDeviceHeight(cxt);
        DisplayImageOptions options = imageUtil.getDisplayImageOptions(
                R.mipmap.default_template_thumb,
                R.mipmap.default_template_thumb,
                R.mipmap.default_template_thumb);

        setTemplateScale(bitmap);
        initTemplateData();
        translate.postTranslate(templateBean.getAndroidImgX() * templateScale,
                templateBean.getAndroidImgY() * templateScale);
        gestures = new GestureDetector(cxt,
                new GestureListener(cxt, this, templateBean));

        templateBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), templatePicMatrix, true);

        ImageLoader.getInstance().loadImage("file://" + mLocPath, options, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                // 得到新的缩放后的图片
                setDragScale(loadedImage);
                dragBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
                        loadedImage.getWidth(), loadedImage.getHeight(), dragPicMatrix, true);
                invalidate();
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });

    }


    //初始化模板的活动区域
    void initTemplateData() {
        leftTopX = (templateBean.getAndroidImgX() - templateBean.getAndroidImgWidth()) * templateScale + defaultBorder;
        leftTopY = (templateBean.getAndroidImgY() - templateBean.getAndroidImgHeight())* templateScale + defaultBorder;
        rightBottomX = (templateBean.getAndroidImgX() + templateBean.getAndroidImgWidth()) *templateScale - defaultBorder;
        rightBottomY = (templateBean.getAndroidImgY() +templateBean.getAndroidImgHeight())* templateScale - defaultBorder;
    }


    //图库图片的缩放比例
    void setDragScale(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 设置想要的大小
        int newWidth = (int)(templateBean.getAndroidImgWidth()* templateScale);
        int newHeight = (int)(templateBean.getAndroidImgHeight()* templateScale);
        // 计算缩放比例
        float scaleWidth = (float) newWidth / width;
        float scaleHeight = (float) newHeight / height;
        // 取得想要缩放的matrix参数
        dragPicMatrix = new Matrix();
        dragPicMatrix.postScale(scaleWidth, scaleHeight);
    }

    void setTemplateScale(Bitmap bitmap) {
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        viewHeight = (int) (deviceHeight - spaceHeight * density);
        templateScale = (float) viewHeight / height;
        viewWidht = (int) (width * templateScale);
        // 取得想要缩放的matrix参数
        templatePicMatrix = new Matrix();
        templatePicMatrix.postScale(templateScale, templateScale);
    }


    public void onAnimateMove(float dx, float dy, long duration) {
        Log.i(LOG_TAG, "onAnimateMove");
        animateStart = new Matrix(translate);
        animateInterpolator = new OvershootInterpolator();
        startTime = System.currentTimeMillis();
        endTime = startTime + duration;
        totalAnimDx = dx;
        totalAnimDy = dy;
        post(new Runnable() {
            @Override
            public void run() {
                onAnimateStep();
            }
        });
    }

    private void onAnimateStep() {
        Log.i(LOG_TAG, "onAnimateStep");
        long curTime = System.currentTimeMillis();
        float percentTime = (float) (curTime - startTime)
                / (float) (endTime - startTime);
        float percentDistance = animateInterpolator
                .getInterpolation(percentTime);
        float curDx = percentDistance * totalAnimDx;
        float curDy = percentDistance * totalAnimDy;
        translate.set(animateStart);
        onMove(curDx, curDy);
        if (percentTime < 1.0f) {
            post(new Runnable() {
                @Override
                public void run() {
                    onAnimateStep();
                }
            });
        }
    }

    public void onMove(float dx, float dy) {
        Log.i(LOG_TAG, "onMove");
        translate.postTranslate(dx, dy);
        RectF rectF = new RectF();
        translate.mapRect(rectF);

        if (rectF.left < leftTopX || rectF.left > rightBottomX
                || rectF.top < leftTopY || rectF.top > rightBottomY) {
            translate.postTranslate(-dx, -dy);
        }
        invalidate();
    }

    public void onResetLocation() {
        translate.reset();
        invalidate();
    }

    public void onSetLocation(float dx, float dy) {
        translate.postTranslate(dx, dy);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(viewWidht, viewHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        if (dragBitmap != null) {
            canvas.drawBitmap(dragBitmap, translate, paint);
        }
        Matrix matrix = new Matrix();
        if (templateBitmap != null) {
            canvas.save();
            matrix.postScale(1f, 1f);
            canvas.drawBitmap(templateBitmap, matrix, paint);
            canvas.restore();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestures.onTouchEvent(event);
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        imageUtil.recycleBitmap(dragBitmap);
        imageUtil.recycleBitmap(templateBitmap);
    }
}
